package pzl.com.canvasapi.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import pzl.com.canvasapi.R;

/**
 * @author zl.peng
 * @version [1.0, 2016-11-23]
 */
public class V_BitmapMesh extends View {
    Bitmap b1, b2;
    int w, h;
    final int WIDTH_UNIT = 100;
    final int HEIGHT_UNIT = 100;
    /**
     * 列数
     */
    int xCount;
    /**
     * 行数
     */
    int yCount;

    /**
     * bitmap　　　　　需要扭曲的源位图
     * meshWidth 　　控制在横向上把该源位图划成成多少格
     * meshHeight 　　控制在纵向上把该源位图划成成多少格
     * verts 　　　　　长度为(meshWidth + 1) * (meshHeight + 1) * 2的数组，它记录了扭曲后的位图各顶点位置
     * vertOffset         控制verts数组中从第几个数组元素开始才对bitmap进行扭曲
     *
     * @param context
     */


    //记录该图片上包含COUNT个顶点
    private int COUNT;
    //定义一个数组,记录Bitmap上的COUNT个点的坐标
    private float[] verts;
    //定义一个数组,记录Bitmap上的COUNT个点经过扭曲后的坐标
    //对图片扭曲的关键就是修改该数组里元素的值
    private float[] orig;

    boolean firstDraw;

    public V_BitmapMesh(Context context) {
        super(context);
    }

    public V_BitmapMesh(Context context, AttributeSet attrs) {
        super(context, attrs);
        /**
         * 出现Immutable bitmap passed to Canvas constructor错误的原因是如果不用copy的方法，直接引用会对资源文件进行修改，而android是不允许在代码里修改res文件里的图片
         */
        b1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.test1).copy(Bitmap.Config.ARGB_8888, true);
        b2 = b1.copy(Bitmap.Config.ARGB_8888, true);
    }

    public V_BitmapMesh(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        init();
        drawImageWithGrid(b1, canvas);

        // 对bitmap按verts数组进行扭曲
        //从第一个点(由第5个参数0控制)开始扭曲
        Log.e("pzl", "xCount=" + xCount);
        Log.e("pzl", "yCount=" + yCount);

        Canvas c = new Canvas(b2);
        drawGrid(0, c);
        canvas.drawBitmapMesh(b2, xCount, yCount, verts, 0, null, 0, null);

    }

    private void drawImageWithGrid(Bitmap image, Canvas canvas) {
        int yOffSet = h;
        Paint paint = new Paint();
        canvas.drawBitmap(image, 0, yOffSet, paint);
        drawGrid(yOffSet, canvas);
    }

    private void drawGrid(int yOffSet, Canvas canvas) {
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(1);
        paint.setColor(Color.BLUE);
        for (int i = 0; i < xCount; i++) {
            for (int j = 0; j < yCount; j++) {
                canvas.drawRect(i * WIDTH_UNIT, yOffSet + j * HEIGHT_UNIT,
                        i * WIDTH_UNIT + WIDTH_UNIT, yOffSet + j * HEIGHT_UNIT + HEIGHT_UNIT, paint);
            }
        }
    }


    private void init() {
        if (firstDraw) return;
        firstDraw = true;

        w = b1.getWidth();
        h = b1.getHeight();
        xCount = w / WIDTH_UNIT;
        yCount = h / HEIGHT_UNIT;
        COUNT = (xCount + 1) * (yCount + 1);
        verts = new float[COUNT * 2];
        orig = new float[COUNT * 2];

        int index = 0;
        for (int y = 0; y <= yCount; y++) {
            float fy = h * (y / (float) yCount);
            Log.e("pzl", "fy=" + fy);
            for (int x = 0; x <= xCount; x++) {
                float fx = w * (x / (float) xCount);
                Log.e("pzl", "fx=" + fx);
                //初始化orig,verts数组
                //初始化,orig,verts两个数组均匀地保存了COUNT个点的x,y坐标　
                orig[index * 2 + 0] = verts[index * 2 + 0] = fx;
                orig[index * 2 + 1] = verts[index * 2 + 1] = fy;
                index += 1;
            }
        }

        Log.e("pzl", "h=" + h);
    }

    private void warp(float cx, float cy) {
        for (int i = 0; i < COUNT * 2; i += 2) {
            float dx = cx - orig[i + 0];
            float dy = cy - orig[i + 1];
            float dd = dx * dx + dy * dy;
            //计算每个坐标点与当前点(cx,cy)之间的距离
            float d = (float) Math.sqrt(dd);
            //计算扭曲度，距离当前点(cx,cy)越远，扭曲度越小
            float pull = 120000 / ((float) (dd * d));
            //对verts数组(保存bitmap　上21 * 21个点经过扭曲后的坐标)重新赋值
            if (pull >= 1) {
                verts[i + 0] = cx;
                verts[i + 1] = cy;
            } else {
                //控制各顶点向触摸事件发生点偏移
                verts[i + 0] = orig[i + 0] + dx * pull;
                verts[i + 1] = orig[i + 1] + dy * pull;
            }
        }
        //通知View组件重绘
        invalidate();
    }

    public boolean onTouchEvent(MotionEvent event) {
        getParent().requestDisallowInterceptTouchEvent(true);
        //调用warp方法根据触摸屏事件的坐标点来扭曲verts数组
        warp(event.getX(), event.getY());
        return true;
    }


}
